package com.darren.framework.interceptor;

import eu.bitwalker.useragentutils.OperatingSystem;
import eu.bitwalker.useragentutils.UserAgent;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class UserAgentInterceptor implements HandlerInterceptor {

	protected Logger logger = LogManager.getLogger(getClass());


	public void afterCompletion(HttpServletRequest request,
								HttpServletResponse response, Object obj, Exception arg3) {

	}

	public void postHandle(HttpServletRequest request, HttpServletResponse response,
						   Object arg2, ModelAndView modelAndView) {

	}

	public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object obj){
		String agentString = request.getHeader("User-Agent");
		UserAgent userAgent = UserAgent.parseUserAgentString(agentString);
		OperatingSystem operatingSystem = userAgent.getOperatingSystem(); // 操作系统信息
		eu.bitwalker.useragentutils.DeviceType deviceType = operatingSystem.getDeviceType(); // 设备类型
		logger.info("User-Agent:{}",agentString);
		switch (deviceType) {
			case COMPUTER:
				logger.info("user device: {}  PC",deviceType.name());
				break;
			case TABLET: {
				if (agentString.contains("Android")){
					logger.info("user device: {}  Android Pad",deviceType.name());
				}else if (agentString.contains("iOS")){
					logger.info("user device: {}  iPad",deviceType.name());
				}else {
					logger.info("user device: {}  Unknown",deviceType.name());
				}
			}
			break;
			case MOBILE: {
				if (agentString.contains("Android")){
					logger.info("user device: {}  Android",deviceType.name());
				}else if (agentString.contains("iOS")){
					logger.info("user device: {}  IOS",deviceType.name());
				}else {
					logger.info("user device: {}  Unknown",deviceType.name());
				}
			}
			break;
			default:
				logger.info("user device: Unknown");
		}
		return true;
	}
}
